package com.hndfsj.common.web;

import java.util.Date;
import java.util.zip.GZIPOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hndfsj.admin.service.IDictionaryService;
import com.hndfsj.common.domain.ByteResources;
import com.hndfsj.common.domain.Values;
import com.hndfsj.common.service.IByteResourcesService;
import com.hndfsj.common.service.IValuesService;
import com.hndfsj.framework.config.Configuration;
import com.hndfsj.framework.utils.FileDownLoadUtil;
import com.hndfsj.framework.utils.HttpUtils;
import com.hndfsj.framework.utils.TranscodeUtil;

/**
 * 项目静态资源文件访问控件同器
 * 
 * @copyright {@link www.hndfsjsoft.com}
 * @author
 * @version 2015年6月29日 下午5:03:23
 * @see com.hndfsj.common.web.controllers.LoginViewController
 */
@Controller("resController")
@RequestMapping(value = "/imgRes")
public class ResourceController {
	public static final String DICTQRCODETYPE = "13";
	@Resource
	IByteResourcesService byteResourcesService;
	@Resource
	IValuesService valuesService;
	@Resource
	IDictionaryService dictionaryService;
	public final static String LOGINDOWNLOAD = "/resource/imgRes/download/";
	public final static String REPORTDOWNLOAD = "/resource/imgRes/report/";
	public final static String DOWNLOADPATH = "/resource/imgRes/img/";
	// 手机的下载
	@RequestMapping(value = "/img/{id}", method = RequestMethod.GET)
	public void getResourceFile(@PathVariable("id") String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ByteResources resources = byteResourcesService.getById(id);
		if (resources != null) {
			// 设置响应头和下载保存的文件名
			String fileName = TranscodeUtil.ISO8859_1FromGBK(resources.getName());
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName+ "\"");
			writerResponseBytes(response, resources.getBytes());
			return ;
		}
		response.setStatus(404);
	}
	// 手机的下载
	@RequestMapping(value = "/download/{id}/{filename}", method = RequestMethod.GET)
	public void downloadMobile(@PathVariable("filename") String file, @PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (StringUtils.isNotBlank(file)) {
			// 文件名（标题+文件路径下文件的后缀名）
			String url = request.getRequestURI();
			if (url.contains(".")) {
				String fileName = file + url.substring(url.lastIndexOf("."));
				// 文件存放的物理路径
				String uploadPath = Configuration.getInstance().getAppPropsValue("file.attach.dir");
				String path = uploadPath + id + "/" + fileName;
				fileName = TranscodeUtil.ISO8859_1FromGBK(fileName);
				java.io.File filePath = new java.io.File(path);
				if (filePath.exists()) {
					String realPath = StringUtils.removeStart(filePath.getPath(), "file:\\");
					FileDownLoadUtil.downLoadAttachement(response, realPath, fileName);
				}
			}
		}
	}
//
	// 手机的下载
	@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
	public void downloadResourceFile(@PathVariable("id") String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if(id.contains(".")){
			id=id.substring(0,id.indexOf("."));
		}
		ByteResources resources = byteResourcesService.getById(id);
		if (resources != null) {
			byte[] result = resources.getBytes();
//			if (resources.getBytes() == null || result.length == 1) {
//				// 抓取文件保存并发送
//				result = HttpUtils.downloadImage(resources.getOriginSrc());
//				resources.setBytes(result);
//				byteResourcesService.update(resources);
//			}
				if(StringUtils.isNotBlank(resources.getName())){
					FileDownLoadUtil.downLoadAttachement(response, result, resources.getName());
				}else{
					// 设置响应头和下载保存的文件名
					writerResponseBytes(response, result);
				}
		} else {
			Values value = valuesService.getById(id);
			if (value != null && StringUtils.isNotBlank(value.getValue())) {
				byte[] result = HttpUtils.downloadImage(value.getValue());
				resources = new ByteResources(id);
				resources.setCreateTime(new Date());
				resources.setOriginSrc(value.getValue());
				resources.setBytes(result);
				byteResourcesService.save(resources);
				writerResponseBytes(response, result);
			}
		}
	}
//
	private void writerResponseBytes(HttpServletResponse response, byte[] result) {
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Encoding", "gzip");// 增加GZIP压缩
		try {
			java.io.OutputStream ops = response.getOutputStream();
			GZIPOutputStream gzipos = new GZIPOutputStream(ops);
			gzipos.write(result);
			gzipos.finish();
			gzipos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//
//	// 二维码生成
//	@RequestMapping(value = "/pager/qrcode", method = RequestMethod.GET)
//	public @ResponseBody MReturnObject qrcode(HttpServletRequest request, HttpServletResponse response)
//			throws Exception {
//		String content = UUIDGenerator.UUIDValue();
//		dictionaryService.save(new Dictionary(content,
//				DateUtils.convertDate2String(DateUtils.DATETIME_SECOND_FORMAT, new Date()) + "$$", DICTQRCODETYPE));
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("qrcode", content);
//		map.put("qrcodeImg", Base64.byteArrayToBase64(QRCodeUtils.getLogoQRCode(content, "/images/qrcodelog.jpg", "")));
//		return new MReturnObject(MReturnObject.SUCCESS, map);
//	}
//
//	// 二维码生成
//	@RequestMapping(value = "/paper/clear/qrcode", method = RequestMethod.GET)
//	public @ResponseBody MReturnObject clearQrcode(@RequestParam("qrcode") String qrcode, HttpServletRequest request,
//			HttpServletResponse response) {
//		Dictionary qrcodeMsg = dictionaryService.getById(qrcode);
//		if (qrcodeMsg != null) {
//			if (checkTime(qrcodeMsg.getValue())) {
//				dictionaryService.deleteById(qrcode);
//			}
//		}
//		return new MReturnObject(MReturnObject.SUCCESS);
//	}
//
//	// 获取二维码通道信息
//	@RequestMapping(value = "/paper/get/qrcode/msg", method = RequestMethod.GET)
//	public @ResponseBody MReturnObject getQrcodeChannelMsg(@RequestParam("qrcode") String qrcode,
//			HttpServletRequest request, HttpServletResponse response) throws Exception {
//		Dictionary qrcodeMsg = dictionaryService.getById(qrcode);
//		if (qrcodeMsg != null) {
//			if (checkTime(qrcodeMsg.getValue())) {
//				ByteResources userMsg = byteResourcesService.getById(qrcode);
//				if (userMsg != null) {
//					return new MReturnObject(MReturnObject.SUCCESS,
//							JSON.parse(userMsg.getBytes(), Feature.OrderedField));
//				}
//				return new MReturnObject(MReturnObject.SUCCESS);
//			}
//		} // TODO 怎么告诉PC端 扫描成功
//		return new MReturnObject(MReturnObject.WARNING, "二维码信息已失效");
//	}
//
//	/**
//	 * 获取二维码通道文书信息
//	 * 
//	 * @param qrcode
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/paper/list", method = RequestMethod.GET)
//	public @ResponseBody MReturnObject paperList(@RequestParam("qrcode") String qrcode, HttpServletRequest request,
//			HttpServletResponse response) throws Exception {
//		return new MReturnObject(MReturnObject.WARNING, "二维码信息已失效");
//	}
//
//	/**
//	 * 下载PDF文档
//	 * 
//	 * @param qrcode
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/download/pdf/{paperId}", method = RequestMethod.GET)
//	public void downloadPdf(@RequestParam("qrcode") String qrcode, @PathVariable("paperId") String paperId,
//			HttpServletRequest request, HttpServletResponse response) throws Exception {
//		Dictionary qrcodeMsg = dictionaryService.getById(qrcode);
//		if (qrcodeMsg != null) {
//			if (checkTime(qrcodeMsg.getValue())) {
//				if (qrcodeMsg.getValue().contains(paperId)) {
//					Paper paper = paperService.getById(paperId);
//					if (paper != null && (paper.getAttachment().endsWith(".doc")||paper.getAttachment().endsWith(".docx"))) {
//						downPdf(response, paper);
//					}
//				}
//			}
//		}
//	}
//
//	@RequestMapping(value = "/download/test/{paperId}", method = RequestMethod.GET)
//	public void test(@PathVariable("paperId") String paperId, HttpServletRequest request, HttpServletResponse response)
//			throws Exception {
//		Paper paper = paperService.getById(paperId);
//		if (paper != null) {
//			downPdf(response, paper);
//		}
//	}
//
//	private void downPdf(HttpServletResponse response, Paper paper) throws IOException {
//		if (StringUtils.isNotBlank(paper.getAttachment())
//				&& paper.getAttachment().startsWith("/resource/imgRes/download/")) {
//			String uploadPath = Configuration.getInstance().getAppPropsValue("file.attach.dir");
//			String path = uploadPath + paper.getAttachment().replace("/resource/imgRes/download", "");
//			java.io.File filePath = new java.io.File(path);
//			if (filePath.exists()) {
//				response.reset();
//				response.setCharacterEncoding("UTF-8");
//				response.setContentType("APPLICATION/OCTET-STREAM");
//				response.setHeader("Content-Disposition",
//						"attachment; filename=\"" + TranscodeUtil.ISO8859_1FromGBK(paper.getName()) + ".pdf\"");
//				PdfUtils.convertAddQrcode(
//						new FileInputStream(filePath), QRCodeUtils
//								.getLogoQRCode("constructionId:" + paper.getConstructId(), "/images/qrcodelog.jpg", ""),
//						response.getOutputStream());
//			}
//		}
//	}
//
//	private String parsePageIds(String[] ids) {
//		String result = "";
//		for (String id : ids) {
//			result += "'" + id + "',";
//		}
//		if (result.contains(","))
//			result = result.substring(0, result.lastIndexOf(","));
//		return result;
//	}
//
//	private boolean checkTime(String value) {
//		Dictionary qrcodeValid = dictionaryService.getById("qrcodeValid");
//		int validTime = 5;
//		try {
//			validTime = Integer.parseInt(qrcodeValid.getValue());
//		} catch (Exception e) {
//		}
//		String[] urls = value.split("\\$\\$");
//		if (urls.length > 0) {
//			try {
//				Date date = DateUtils.parseDateTimeWithSecond(urls[0]);
//				if ((new Date().getTime() - date.getTime()) < 60000 * validTime) {
//					return true;
//				}
//			} catch (Exception e) {
//			}
//		}
//		return false;
//	}

}
